<template>
	<view class="content-box">
		<view class="gameArea">
			<view v-show="props.seed===0" :class="'colClass col-'+index" v-for="(items,index) in colNum" :key="index">
				<view :class="'col col-'+index" v-for="(item,i) in colArrObj[items]"
					:style="returnTransform(colArrObj[items],i)" :key="i">
					<everyBlock :type="item" :col="items" :activeStatus="colArrObj[items]&&colArrObj[items].length-1==i"
						@clickItem="clickItem" :disabled="props.disabled"></everyBlock>
				</view>
			</view>
			<view v-show="props.seed===1" style="display: flex;flex-wrap: wrap;">
				<view
					style="display: flex;flex-wrap: wrap;width: 33%;height: 33%;box-sizing: border-box;border: 1rpx solid #ccc;"
					v-for="items in Object.keys(seedArrObj)" :key="items">
					<view class="area" v-for="item in Object.keys(seedArrObj[items])" :key="item">
						<view :class="`everyBlock col-${item}`" v-for="(i,index) in seedArrObj[items][item]" :key="i"
							:style="`transform: translate(${5*index}%, ${5*index}%);z-index:${i.index}`">
							<everyBlock :type="i.value" :col="Number(item)" :area="Number(items)"
								:activeStatus="seedArrObj[items][item].length-1==index" @clickItem="clickItem"
								:disabled="returnDisabledFn(seedArrObj[items],i)"></everyBlock>
						</view>

					</view>
				</view>
			</view>
			<view class="otherRow">
				<view class="" v-for="(item,index) in otherArr" :key="item" style="padding: 0 5rpx;">
					<everyBlock :type="item" :otherIndex="index" noStyle @clickOtherItem="clickOtherItem"></everyBlock>
				</view>
			</view>
			<view class="resultRow">
				<view class="" v-for="item in resultArr" :key="item + new Date().getTime()+''" style="padding: 0 5rpx;">
					<everyBlock :type="item" disabled noStyle></everyBlock>
				</view>
			</view>
		</view>
		<view class="property">
			<van-button type="default" @click="moveCard">
				<i class="iconfont icon-liucheng"></i>
			</van-button>
			<van-button type="default" @click="reBack">
				<i class="iconfont icon-lishijilu"></i>
			</van-button>
			<van-button type="default" @click="reInit">
				<i class="iconfont icon-suiji"></i>
			</van-button>
		</view>
	</view>
</template>

<script setup>
	import {
		computed,
		onBeforeMount,
		onMounted,
		ref,
		watchEffect
	} from "vue";
	import everyBlock from "./everyBlock.vue"
	components: {
		everyBlock
	}
	//-------------数据传递
	const props = defineProps({
		seed: Number,
		disabled: Boolean
	})
	//-------------变量定义
	let colArrObj = ref({})
	let resultArr = ref([])
	let otherArr = ref([])
	let seedArrObj = ref({})
	let oldColArrObj = ref({})
	let oldResultArr = ref([])
	let oldOtherArr = ref([])
	let oldSeedArrObj = ref({})
	//-------------常量定义
	const emit = defineEmits(["hasRusult"])
	const colNum = 36
	const unitLength = 4 //定义区域  取决于colNum  最好是正方形好做区域划分
	const regionObj = {
		0: {
			0: [],
			1: [],
			2: [],
			3: []
		},
		1: {
			0: [],
			1: [],
			2: [],
			3: []
		},
		2: {
			0: [],
			1: [],
			2: [],
			3: []
		},
		3: {
			0: [],
			1: [],
			2: [],
			3: []
		},
		4: {
			0: [],
			1: [],
			2: [],
			3: []
		},
		5: {
			0: [],
			1: [],
			2: [],
			3: []
		},
		6: {
			0: [],
			1: [],
			2: [],
			3: []
		},
		7: {
			0: [],
			1: [],
			2: [],
			3: []
		},
		8: {
			0: [],
			1: [],
			2: [],
			3: []
		}
	}


	//-------------加载初始化
	onBeforeMount(() => {
		initFn()
	})

	//-------------判断当前是否可以点击
	const returnDisabledFn = (areaObj, data) => {
		let maxIndex = 0
		Object.keys(areaObj).forEach(key => {
			areaObj[key].forEach(item => {
				if (item.index > maxIndex) {
					maxIndex = item.index
				}
			})
		})
		return props.disabled || data.index < maxIndex
	}
	// ---------------输赢遍历
	watchEffect(() => {
		if (resultArr.value.length && resultArr.value.length > 2) {
			//遍历判断是否存在可以删除的部分
			let obj = {}
			for (var i = 0; i < resultArr.value.length; i++) {
				if (obj[resultArr.value[i]]) {
					obj[resultArr.value[i]].times++
				} else {
					obj[resultArr.value[i]] = {
						times: 1,
					}
				}
			}
			Object.keys(obj).forEach(key => {
				if (obj[key].times == 3) {
					resultArr.value = resultArr.value.filter(item => item != key)
					getAudio()
				}
			})
		}
		//没有可以消除的  判断是否输了 ps：大于7个
		if (resultArr.value.length >= 7) {
			//输了
			emit("hasRusult", false, props.seed)
		} else if (Object.keys(colArrObj.value).length != 0 && props.seed === 0) {
			//判断是否赢了
			let win = true
			Object.keys(colArrObj.value).forEach(key => {
				if (colArrObj.value[key].length != 0) {
					win = false
				}
			})
			if (win) {
				if (resultArr.value.length == 0) {
					emit("hasRusult", true, props.seed)
				} else {
					emit("hasRusult", false, props.seed)
				}
			}
		} else if (JSON.stringify(seedArrObj.value) != '{}') {
			if (props.seed === 1 && seedArrObj.value[0][0].length == 0) {
				let win = true
				Object.keys(seedArrObj).forEach(keys => {
					Object.keys(seedArrObj[keys]).forEach(key => {
						if (seedArrObj[keys][key] && seedArrObj[keys][key].length != 0) {
							if (seedArrObj[keys][key].length != 0) {
								win = false
							}
						}
					})
				})
				if (win) {
					if (resultArr.value.length == 0) {
						emit("hasRusult", true, props.seed)
					} else {
						emit("hasRusult", false, props.seed)
					}
				}
			}
		}
	})
	//-------------消除音效
	const getAudio = (src = "/static/material/iKun/audio/ji.mp3") => {
		const innerAudioContext = uni.createInnerAudioContext();
		innerAudioContext.src = src;
		innerAudioContext.play()
	}
	//-------------层级显示
	const returnTransform = (arr, i) => {
		if (i == arr.length - 1) {
			return 'transform: translate(' + (i * 5) + '%,' + (i * 5) + '%);z-index:' + i + ''
		} else {
			return 'transform: translate(' + (i * 4) + '%,' + (i * 4) + '%);z-index:' + i + ''
		}
	}
	//--------------随机列点击事件
	const clickItem = (col, area) => {
		remenberFn()
		if (area || area === 0) {
			let temp = seedArrObj.value[area][col][seedArrObj.value[area][col].length - 1]
			seedArrObj.value[area][col].splice(seedArrObj.value[area][col].length - 1, 1)
			resultArr.value.push(temp.value)
		} else {
			resultArr.value.push(colArrObj.value[col].pop())
		}
	}
	const remenberFn = () => {
		oldResultArr.value = JSON.parse(JSON.stringify(resultArr.value))
		oldOtherArr.value = JSON.parse(JSON.stringify(otherArr.value))
		oldSeedArrObj.value = JSON.parse(JSON.stringify(seedArrObj.value))
		oldColArrObj.value = JSON.parse(JSON.stringify(colArrObj.value))
	}
	//-------------初始化
	const initFn = () => {
		colArrObj.value = {}
		resultArr.value = []
		seedArrObj.value = JSON.parse(JSON.stringify(regionObj))
		//测试一下生成随机数列
		if (props.seed === 0) {
			let types = 4
			let cols = 12 //固定展示的图片位置 意味着行数应该是固定的  第一关固定为12列  列数为9.10.11.15.19.22.26.29.33.37.38.39
			let arr = [] //生成所有类型的数组 然后分段取给每一列
			let indexArr = [9, 10, 14, 17, 20, 23, 26, 29, 33, 34]
			arr = productArr(types, 2) //循环种类的两倍
			//打乱arr种子序号
			randomArr(arr)
			//以下循环不报错的前提是arr.length/cols必须为整数 也就是随机数组必须等于有值列的倍数
			let temp = 0
			for (var i = 0; i < colNum; i++) {
				if (indexArr.includes(i)) {
					//等比插入
					colArrObj.value[i] = arr.slice(temp * (arr.length / cols), (arr.length / cols) * (temp + 1))
					temp++
				} else {
					colArrObj.value[i] = []
				}
			}
		} else if (props.seed === 1) {
			let types = 6
			let times = 11
			let arr = []
			arr = productArr(types, times)
			//arr --->一个随机的以3为组的多组打乱顺序的数组
			randomArr(arr)
			//这里应该划分区域 
			randomInsertSeed(arr)
		}
	}
	//-------------随机生成区域 --seed =1
	const randomInsertSeed = (arr) => {
		let tempObj = {}
		if (arr && arr.length != 0) {
			arr.forEach(item => {
				let randomRegion = parseInt(Math.random() * (Object.keys(regionObj).length))
				if (tempObj[randomRegion] && tempObj[randomRegion].length != 0) {
					tempObj[randomRegion] = [...tempObj[randomRegion], item]
				} else {
					tempObj[randomRegion] = [item]
				}
			})
		}
		//这里已经区分了区域 为tempObj  键值是区域 值为区域的随机数组
		Object.keys(regionObj).forEach(topKey => {
			randomRandomCol(tempObj[topKey], topKey)
		})
		//这里根据区域和区域列分好了数据 seedArrObj 
		console.log(seedArrObj.value)
	}
	//提取随机方法  在随机的列中放入随机长度的数组
	const randomRandomCol = (tempArr, topKey, maxIndex = 0) => {
		let isDone = true
		// let randomRegion = parseInt(Math.random() * (Object.keys(tempArr).length) / 2) //  [0 - 区域总数/4)
		let randomCol = parseInt(Math.random() * 4) //   [0-4)
		tempArr.length != 0 ? isDone = false : ""
		if (!isDone) {
			if (tempArr.length > randomCol) {
				for (var i = 0; i < randomCol; i++) {
					let obj = {
						value: tempArr[i],
						index: maxIndex
					}
					if (i % 4 == 0) {
						seedArrObj.value[topKey][i].push(obj)
					} else {
						seedArrObj.value[topKey][4 - i].push(obj)
					}
				}
				tempArr.splice(0, randomCol)
				maxIndex++
			} else {
				for (var i = 0; i < tempArr.length; i++) {
					let obj = {
						value: tempArr[i],
						index: maxIndex
					}
					if (i % 2 == 0) {
						seedArrObj.value[topKey][i].push(obj)
					} else {
						seedArrObj.value[topKey][4 - i].push(obj)
					}
				}
				tempArr = []
				maxIndex++
			}

			if (tempArr.length > 0) {
				randomRandomCol(tempArr, topKey, maxIndex)
			}
		}
	}

	//-------------随机插入事件 --seed =0
	const randomInsert = (arr, cols, sum, nullArr = [], col = 0) => {
		if (!nullArr.includes(col)) {
			let spliceNum = parseInt(Math.random() * (sum / cols)) + 1
			if (spliceNum < arr.length) {
				let tempArr = arr.splice(0, spliceNum)
				if (colArrObj.value[col]) {
					colArrObj.value[col] = [...colArrObj.value[col], ...tempArr]
				} else {
					colArrObj.value[col] = [...tempArr]
				}
			}
			col++
			if (col > cols) {
				col = 0
			}
			if (arr.length >= parseInt(sum / cols) + 1) {
				randomInsert(arr, cols, sum, nullArr, col)
			} else {
				if (colArrObj.value[col]) {
					colArrObj.value[col] = [...colArrObj.value[col], ...arr]
				} else {
					colArrObj.value[col] = [...arr]
				}
			}
		} else {
			col++
			if (col == cols) {
				col = 0
			}
			randomInsert(arr, cols, sum, nullArr, col)
		}
	}
	//-------------生成列
	const productArr = (types, everyType) => {
		let arr = []
		for (var i = 0; i < types * everyType; i++) {
			let type = parseInt(Math.random() * (types + 1))
			arr = [...arr, type, type, type]
		}
		return arr
	}
	//-------------产生随机生成的序列
	const randomArr = (arr, randomTime = 300) => {
		if (arr && arr.length != 0) {
			for (var i = 0; i < randomTime; i++) {
				let indexA = parseInt(Math.random() * arr.length)
				let indexB = parseInt(Math.random() * arr.length)
				let temp = arr[indexA]
				arr[indexA] = arr[indexB]
				arr[indexB] = temp
			}
		}
	}
	//-------------点击协助数据列
	const clickOtherItem = (index) => {
		resultArr.value.push(...otherArr.value.splice(index, 1))
	}
	//-------------移出三张card到other卡池中
	const moveCard = () => {
		if (resultArr.value.length >= 3 && otherArr.value.length <= 4) {
			remenberFn()
			otherArr.value.push(...resultArr.value.splice(0, 3))
		} else {
			console.log("不能撤回")
		}
	}
	//-------------撤回
	const reBack = () => {
		if (resultArr.value.length != oldResultArr.value.length) {
			resultArr.value = JSON.parse(JSON.stringify(oldResultArr.value))
			otherArr.value = JSON.parse(JSON.stringify(oldOtherArr.value))
			seedArrObj.value = JSON.parse(JSON.stringify(oldSeedArrObj.value))
			colArrObj.value = JSON.parse(JSON.stringify(oldColArrObj.value))
		} else {
			console.log("大哥？")
		}
	}
	//-------------重新打乱
	const reInit = () => {
		
	}
	//-------------向外主动暴露初始化方法
	defineExpose({
		initFn
	})
</script>

<style scoped>
	.content-box {
		display: flex;
		justify-content: space-around;
		align-items: center;
		flex-direction: column;
	}

	.gameArea {
		display: flex;
		flex-wrap: wrap;
		justify-content: center;
		align-items: center;
		width: 600rpx;
		height: 1000rpx;
		padding: 80rpx 50rpx 0 50rpx;
		border: 1rpx solid #ccc;
		box-sizing: border-box;
	}

	.otherRow {
		height: 60rpx;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.resultRow {
		height: 100rpx;
		width: 100%;
		display: flex;
		align-items: center;
		border: 1px solid #ccc;
	}

	.colClass {
		width: 60rpx;
		height: 80rpx;
		box-sizing: border-box;
		position: relative;
		margin: 0 10rpx;
	}

	.colClass .col:first-child {
		transform: translate(0, 0) !important;
	}

	.col {
		position: absolute;
	}

	.property {
		width: 600rpx;
		height: 150rpx;
		border: 1rpx solid #ccc;
		box-sizing: border-box;
		display: flex;
		justify-content: space-around;
		align-items: center;
	}

	.area {
		position: relative;
		box-sizing: border-box;
		width: 70rpx;
		height: 80rpx;
		padding: 2rpx 5rpx;
	}

	.everyBlock {
		position: absolute;
	}
</style>